package diva.pap;

import static diva.android_library.lang.AndroidLang.event;
import static diva.lib.lang.Lang.set;

import android.content.Context;
import diva.android_library.rpc.Response;
import diva.lib.event.Event;
import diva.lib.json.JSONArray;
import diva.lib.json.JSONObject;
import diva.lib.net.UrlBuilder;
import diva.pap.model.RequestBase;

public class TransactionsRequest extends RequestBase<TransactionsRequest> {

  private int from;
  private int to;
  private String fromtime;
  private JSONObject rowData;
  private final Event<Void> onLoaded = event();

  public TransactionsRequest() {
    super(null, "load_transactions", null);
  }

  public Event<Void> eventLoaded() {
    return onLoaded;
  }

  public int getAllItemsCount() {
    return data.getNumber("all_count").intValue();
  }

  public String getFromTime() {
    return data.getString("fromtime");
  }

  public JSONObject getRow(int position) {
    JSONArray rows = data.get("rows").asArray();
    rowData = rows.get(position).asObject();
    return rowData;
  }

  @Override
  public UrlBuilder getUrl() {
    UrlBuilder url = super.getUrl().add("from", from).add("to", to);
    if (set(fromtime)) url.add("fromtime", fromtime);
    return url;
  }

  public void initialize(Context context, int from, int to) {
    setContext(context);
    this.from = from;
    this.to = to;
  }

  public void initialize(int from, int to, String fromtime) {
    this.from = from;
    this.to = to;
    this.fromtime = fromtime;
  }

  @Override
  protected void onRequestSuccess(Response<TransactionsRequest> response) {
    super.onRequestSuccess(response);
    onLoaded.run(null);
  }

}